package org.desktop.diskutils.components.treemap.renderers;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.geom.Rectangle2D;

import org.desktop.diskutils.components.treemap.TreeBuilder;

import prefuse.render.LabelRenderer;
import prefuse.visual.VisualItem;
import prefuse.visual.tuple.TableDecoratorItem;

public class TreeMapLabelRenderer extends LabelRenderer {

//	private static final double ROTATION_RESILIENCE = 1.5;

	public TreeMapLabelRenderer() {
		super(TreeBuilder.LABEL_ATTR);
	}

//	@Override
//	public void render(Graphics2D g, VisualItem item) {
//		String txt = super.getText(item);
//
//		Rectangle2D bounds = item.getBounds();
//		if (item instanceof TableDecoratorItem) {
//			bounds = ((TableDecoratorItem) item).getDecoratedItem().getBounds();
//		}
//		Font font = m_font;
//
//		FontMetrics fontMetrics = DEFAULT_GRAPHICS.getFontMetrics(font);
//		int stringW = fontMetrics.stringWidth(txt);
//		int stringH = fontMetrics.getAscent();
//
//		boolean fitsHorizontally = stringW < bounds.getWidth() && stringH < bounds.getHeight();
//		boolean fitsVertically = stringH < bounds.getWidth() && stringW < bounds.getHeight();
//
//		if (fitsVertically && (!fitsHorizontally || bounds.getWidth() * ROTATION_RESILIENCE < bounds.getHeight())) {
//			AffineTransform tr = new AffineTransform();
//			tr.rotate(-Math.PI / 2);
//			Font newFont = font.deriveFont(tr);
//			m_font = newFont;
//			super.render(g, item);
//			// Return the previous font.
//			// Otherwise others will be affected as well
//			m_font = font;
//		} else {
//			super.render(g, item);
//		}
//
//	}

	@Override
	protected String getText(VisualItem item) {
		String txt = super.getText(item);
		Rectangle2D bounds = ((TableDecoratorItem) item).getDecoratedItem().getBounds();
		Font font = item.getFont();

		FontMetrics fontMetrics = DEFAULT_GRAPHICS.getFontMetrics(font);
		int stringW = fontMetrics.stringWidth(txt);
		int stringH = fontMetrics.getAscent();

		boolean fitsHorizontally = stringW < bounds.getWidth() && stringH < bounds.getHeight();
//		boolean fitsVertically = stringH < bounds.getWidth() && stringW < bounds.getHeight();

		if (!fitsHorizontally) {
			txt = null;
		}
		return txt;
	}

}
